<?php

namespace Admin\Controller;

use Think\Controller;
use Common\Util\UploadHandler;
use Common\Controller\AdminbaseController;

class CouponController extends AdminbaseController {
	private $_code_type_conf = array (
			1 => '减免券',
			2 => '代金券' 
	);
	private $_code_expiry_conf = array (
			1 => '无限制',
			2 => '指定日期',
			3 => '指定天数' 
	);
	
	public function index() {
		$Model = D ( 'CouponCode' );
		
		
		$where = array('is_active' => array('neq', 0));
		$key = I('get.key');
		
		if ($key) {
			$where ['title'] = array('like', '%'.$key.'%');
		}
		
		$list = $Model->where($where)->select ();
		
		$this->assign ( 'list', $list );
		$this->display ();
	}
	
	public function add() {
		if (! IS_POST) {
			$this->assign ( 'code_type_conf', $this->_code_type_conf );
			$this->assign ( 'code_price_conf', $this->_code_price_conf );
			$this->assign ( 'code_expiry_conf', $this->_code_expiry_conf );
			
			$this->display ();
		} else {
			$Model = D ( 'CouponCode' );
			
			$data = I ( 'post.' );
			$data = array (
				'title' => I ( 'title'),
				'c_type' => I ( 'c_type'),
				'expiry_type' => I ( 'expiry_type'),
				'addtime' => time () 
			);
			
			if (I ( 'c_type') == 1) {
				$data ['money_max'] = floatval ( I ( 'money_max') );
				$data ['money_reduce'] = floatval ( I ( 'money_reduce') );
			} elseif (I ( 'c_type') == 2) {
				$data ['money_amount'] = floatval ( I ( 'money_amount') );
			}
			
			if (I ( 'expiry_type') == 1) {
				$data ['expiry'] = 0;
			} else if (I ( 'expiry_type') == 2) {
				$data ['expiry'] = strtotime ( I ( 'expiry') . ' 23:59:59' );
			} else {
				$data ['expiry'] = I ( 'expiry');
			}
			
			$c_id = 0;
			if ($c_id = $Model->add ( $data )) {
				// 插入附属表数据
				$data = array (
					'c_id' => $c_id,
					'fetch_limit' => I ( 'fetch_limit'),
					'directions' => I ( 'directions'),
					'prompt' => I ( 'prompt')
				);
				$ccdModel = D ( 'CouponCodeData' );
				$ccdModel->add ( $data );
				
				$this->success ( '添加成功', U ( '/Admin/Coupon/index' ) );
			} else {
				$this->error ( '添加失败' );
			}
		}
	}
	
	public function edit() {
		if (! IS_POST) {
			$id = I ( 'get.id' );
			
			$Model = D ( 'CouponCode' );
			$couponInfo = $Model->getCouponInfo($id);
			
			$this->assign ( 'code_type_conf', $this->_code_type_conf );
			$this->assign ( 'code_price_conf', $this->_code_price_conf );
			$this->assign ( 'code_expiry_conf', $this->_code_expiry_conf );
			
			$this->assign ( 'code', $couponInfo );
			$this->display ();
		} else {
			$Model = D ( 'Beautician' );
			if ($Model->updateInfo ( I ( 'post.' ) )) {
				$this->success ( '修改成功', U ( '/Admin/Beautician/index' ) );
			} else {
				$this->error ( $Model->getError () );
			}
		}
	}
	
	public function delete() {
		$id = I ('get.id');
		$Model = D('CouponCode');
		 
		$item = $Model->getCouponInfo($id);
		if (!$item ['is_active']) {
			$this->success('删除成功');
		} else {
			$data = array('is_active' => 0);
			$result = $Model->where(array('id' => $id))->save($data);
			if ($result) {
				$Model->clearCache($id);
				$this->success('删除成功');
			} else {
				$this->error('删除失败');
			}
		}
	}
	
	/**
	 * 查询用户优惠券
	 */
	public function userCoupon() {
		
		$couponName = I('get.key');
		$userId = I('get.user_id');
		$couponId = I('get.coupon_id');
		
		$where = array();
		if ($couponId) {
			$where ['coupon_id'] = $couponId;
		} else if ($couponName) {
			$where ['coupon_title'] = array('like', '%'.$couponName.'%');
		}
		
		if ($userId) {
			$where ['user_id'] = $userId;
		}
		
		$list = M('user_coupon')->where($where)->select();
		$this->assign('list', $list);
		$this->display();
	}
	
	public function deleteUserCoupon() {
		$userCouponModel = M('user_coupon');
		 
		if (!IS_POST) {
			$id = I ('get.id');
			 
			$result = $userCouponModel->where(array('id' => $id))->save(array('status' => 0));
			if ($result) {
				$operation = array('operation_object_id' => $id);
				\Think\Hook::listen('operation', $operation);
				 
				$this->ajaxReturn(array('status' => 1, 'url' => U('userCoupon')));
			} else {
				$this->ajaxReturn(array('status' => 0));
			}
		} else {
			$ids = I ('post.ids');
			if (count($ids) == 1) {
				$where = array('id' => $ids[0]);
				$result = $userCouponModel->where($where)->save(array('status' => 0));
			} else {
				$where ['id'] = array('in', implode(',',$ids));
				$result = $userCouponModel->where($where)->save(array('status' => 0));
			}
			 
			if (!$result) {
				$this->ajaxReturn(array('status' => 0 ));
			}
			 
			foreach ($ids as $couponId) {
				$operation = array('operation_object_id' => $couponId);
				\Think\Hook::listen('operation', $operation);
			}
			 
			$this->ajaxReturn(array('status' => 1, 'url' => U('userCoupon')));
		}
	}
	
	public function hasUseCoupon() {
		$couponName = I('get.key');
		$userId = I('get.user_id');
		$couponId = I('get.coupon_id');
		
		$where = array('status' => 2);
		if ($couponId) {
			$where ['coupon_id'] = $couponId;
		} else if ($couponName) {
			$where ['coupon_title'] = array('like', '%'.$couponName.'%');
		}
		
		if ($userId) {
			$where ['user_id'] = $userId;
		}
		
		$list = M('user_coupon')->where($where)->select();
		$this->assign('list', $list);
		$this->display('userCoupon');
	}
	
	function ban(){
		$id=intval($_GET['id']);
		if ($id) {
			$couponModel = D ( 'CouponCode' );
			$rst = $couponModel->where(array("c_id"=>$id))->setField('is_active','2');
			if ($rst) {
				$this->success("优惠券停用成功！", U("index"));
			} else {
				$this->error('优惠券停用失败！');
			}
		} else {
			$this->error('数据传入失败！');
		}
	}
	
	function cancelban(){
		$id=intval($_GET['id']);
		if ($id) {
			$couponModel = D ( 'CouponCode' );
			$rst = $couponModel->where(array("c_id"=>$id))->setField('is_active','1');
			if ($rst) {
				$this->success("优惠券启用成功！", U("index"));
			} else {
				$this->error('优惠券启用失败！');
			}
		} else {
			$this->error('数据传入失败！');
		}
	}
	
	/**
	 * 发放优惠券
	 */
	public function sendCoupon() {
		if (!IS_POST) {
			$list = D('CouponCode')->select();
			$this->assign('coupons', $list);
			
			$userList = D('User')->group('open_id')->select();
			$citys = D('User')->field(array('select_city'))
				->where(' select_city!="0" AND select_city!="40" ')->group('select_city')->select();
			
			$this->assign('citys', $citys);
			$this->assign('userList', $userList);
			$this->display();
		} else {
			$couponid = I ('post.coupon_id');
			$CouponCodeModel = D('CouponCode');
			
			$couponInfo = $CouponCodeModel->getCouponInfo($couponid);
			$users = I('post.userId');
			
			$error = array();
			if ($users) {
				$UserCouponModel = D('UserCoupon');
				
				$expires_time = $couponInfo ['expiry_type'] == '3'? time() + $couponInfo ['expiry'] * 24 * 3600:$couponInfo ['expiry'];
				$couponData = array(
					'coupon_title' => $couponInfo ['title'],
					'coupon_id' => $couponInfo ['c_id'],
					'c_type' => $couponInfo ['c_type'],
					'money_max' => $couponInfo ['money_max'],
					'money_reduce' => $couponInfo ['money_reduce'],
					'money_amount' => $couponInfo ['money_amount'],
					'expiry_type'	=> $couponInfo ['expiry_type'],
					'expires_time' => $expires_time,
					'status' => 1,
					'created' => time(),
				);
				
				foreach ($users as $key => $userId) {
					$couponData ['user_id'] = $userId;
					
					$addResult = $UserCouponModel->add($couponData);
					if (!$addResult) {
						$error [] = $userId;
					}
				}
			}
			
			$this->success('发送优惠券完成');
		}
	}
}